package com.example.demo1.activity

import ArticleViewModel
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.example.demo1.R
import com.example.demo1.adapter.MyViewPagerAdapter
import com.example.demo1.databinding.ActivityArtitleBinding
import com.example.demo1.databinding.ActivityEditInfoBinding
import com.example.demo1.databinding.ActivityReadStoryBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
/**
 * 适趣文常知识读一读界面activity
 * **/
class ReadStoryActivity : AppCompatActivity() {
    private lateinit var binding: ActivityReadStoryBinding
    private val viewModel:ArticleViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityReadStoryBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
        viewModel.fetchReadArticleData()
        lifecycleScope.launch {
            viewModel.articleReadListStateFlow.collect {
                if (it.isNotEmpty()) {
                    binding.progressBar.max=it.size
                    binding.viewPager.adapter=MyViewPagerAdapter(this@ReadStoryActivity,it)
                }
            }
        }
    }

    private fun initView() {
        setSupportActionBar(binding.toolbar2)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.setDisplayShowTitleEnabled(false)
        binding.toolbar2.navigationIcon =
            resources.getDrawable(R.drawable.baseline_arrow_back_ios_24)
        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                binding.progressBar.progress=position+1
                binding.progressHint.text="${position+1} / ${binding.progressBar.max}"
            }
        })
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        com.example.utils.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
    }
}